package com.bm.fifter;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bm.Result.CodeEnum;
import com.bm.Result.Result;
import com.bm.constant.Constants;
import com.bm.util.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author 86134
 * @version 1.0
 * @description TODO
 * @date 2024/2/28 15:17
 */
//@Component
public class TokenVerifyFilter extends OncePerRequestFilter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //如果是登录请求就放行
        String requestURI = request.getRequestURI();
        if(requestURI.equals(Constants.CAPTCHA_URL) || requestURI.equals(Constants.LOGIN_URL) || requestURI.equals(Constants.SWAGGER_DOC) ){
            //是登录的请求直接放行
            filterChain.doFilter(request,response);

        }else{
            String token = request.getHeader("Authorization");
            //token为空的话
            if(!StringUtils.hasText(token)){
                Result result = Result.FAIL(CodeEnum.USER_IS_NOT_LOGIN);
                ResponseUtils.write(response, JSONUtil.toJsonStr(result));
                return;
            }
            //从redis中获取token
            String redisToken = stringRedisTemplate.opsForValue().get(Constants.VALIDATE_CODE_REDIS_KEY + token);
            if(!StringUtils.hasText(redisToken)){
                //从redis中获取的token为空的话
                Result result = Result.FAIL(CodeEnum.TOKEN_IS_EMPTY);
                String resultJson = JSONUtil.toJsonStr(result);
                ResponseUtils.write(response,resultJson);
                return;
            }
            //进行token的比较
            if(!redisToken.equals(token)){
                //token不一致的话
                Result result = Result.FAIL(CodeEnum.TOKEN_IS_NONE_MATCH);
                String resultJson = JSONUtil.toJsonStr(result);
                ResponseUtils.write(response,resultJson);
                return;
            }
            //token通过 延长token时间 5分钟
            stringRedisTemplate.opsForValue().set(Constants.REDIS_TOKEN_KEY+token,token,5, TimeUnit.MINUTES);

            filterChain.doFilter(request, response);
        }
    }
}
